const App = getApp()
import { GoodsModel } from '../../models/goods.js'
const ModelGoods = new GoodsModel()
import { AppModel } from '../../models/app.js'
import { decodeUnicode, random } from '../../utils/index.js'
const ModelApp = new AppModel()
import { ManagerModel } from '../../models/manager'
const managerModel = new ManagerModel()
import { MineModel } from '../../models/mine'
const mineModel = new MineModel()
import $CountDown from '../../utils/countdown.js'
import { HomeModel } from '../../models/home.js'
const ModelHome = new HomeModel()
import { SeckillModel } from '../../models/seckill'
const ModelSeckill = new SeckillModel()

Page({
  /**
   * 页面的初始数据
   */
  data: {
    isLogined: true,
    showShare: false,
    cartStatus: 2, //购物车状态：1APP，2小程序
    id: '',
    goodsDetail: {},
    showList: [],
    skuVisible: false,
    specList: [],
    stock: 10,
    goodsNum: 1,
    thumb: '',
    shareImg: '',
    startDate: null,
    endDate: null,
    activeIndex: null,
    evaluateNum: null,
    evaluate: {},
    loading: false,
    showService: false,
    serviceInfo: {},
    shopCartNum: 0,
    iphoneX: App.globalData.isIphoneX,
    days: 0,
    hours: 0,
    min: 0,
    sec: 0,
    isBack: false,
    loadDone: false,
    floorstatus: false,
    guideVisible: false,
    guideInfo: {},
    showType: '',
    saleOff: false,
    more: '', // 加载专场
    specialNotice: '',
    userType: '',
    wiggle: true,
    showCard: false,
    statusBarHeight: App.globalData.statusBarHeight,
    isTabbar: false,
    minBanner: [],
    hotGoods: [],
    specialId: '',
    goodsStatus: '',
    specialCode: '',
    seckillDate: '',
    seckill: false,
    seckillNow: false,
    secKillTomorrow: false,
    quicklyStatus: '', //0未预约快抢 1 已预约快抢
    seckillId: '', //快抢id
    seckillGoodsId: '', //快抢商品id
    specialInfo: '', //关联专场
    showGuide: false
  },

  onLoad: function(options) {
    console.log('goods onLoad==', options)
    // 扫码二维码进入 encodeURIComponent
    if (options.scene) {
      let scene = decodeURIComponent(options.scene)
      //&是我们定义的参数链接方式
      this.data.bossid = scene.split('&')[0]
      this.data.id = scene.split('&')[1]
      this.data.scode = scene.split('&')[2]
    } else {
      // 好友链接或上个页面进入
      this.data.bossid = options.bossid
      this.data.id = options.id // 商品id
      this.data.scode = options.scode ? options.scode : '' // 活动专场code
    }
    // 存储bossid
    wx.setStorageSync('bossid', this.data.bossid)
    // 初始化数据
    this.init()
    // 最后疯抢
    this.getBannerList()
    // 隐藏右上角分享功能
    wx.hideShareMenu()
  },
  onShow() {
    // 获取购物车数量
    if (this.data.shopCartNum > 0) {
      this.selectCartNumber()
    }
    this.setGio()
  },
  // 统计
  setGio() {
    let info = this.data.goodsDetail
    // 没有请求到数据的时候不统计
    if (!info.goodsName) {
      return
    }
    App.globalData.gio('setPage', {
      GdTitle: '商品详情页',
      GdID: this.data.id, // 商品id
      GdName: info.goodsName, // 商品名称
      GdBrand: info.brandName, // 商品品牌
      GdCode: info.goodsCode // 商品款号
    })
  },

  // 登陆成功，由login组件触发
  loginSuccess() {
    this.setData({
      isLogined: true
    })
    // 成功后操作
    // 获取购物车数量
    this.selectCartNumber()
    // 获取商品详情
    this.getGoodsDetail()
    // 获取粉丝
    this.getFans()

    //检测本页
    this.getPrePage()
  },
  // 用户登录
  init() {
    const _this = this
    App.getVipInfo(function(userInfo) {
      if (!userInfo) {
        console.log('没有token,获取用户信息失败')
        _this.setData({
          isLogined: false
        })
        // 有用户信息了可以正常请求数据
      } else {
        // 获取购物车数量
        _this.selectCartNumber()
        // 获取商品详情
        _this.getGoodsDetail()
        // 获取粉丝
        _this.getFans()
        //检测本页
        _this.getPrePage()
      }
    })
  },
  //检测上一页
  getPrePage() {
    const that = this
    const pages = getCurrentPages()
    // const currPage = pages[pages.length - 1]; //当前页面
    // const prevPage = pages[pages.length - 2]; //上一个页面
    if (pages.length == 1) {
      that.setData({
        isTabbar: true
      })
    }
  },
  // 组件触发显示售后
  doShowService() {
    const _this = this
    App.queryServiceInfo(function(serviceInfo) {
      _this.setData({
        showService: true,
        serviceInfo: serviceInfo
      })
    })
  },
  // 最多最少
  trigger(e) {
    const type = e.detail.type
    // 最多
    if (type === 'add') {
      App.WxService.showToast({ title: '不能再加多了哦', icon: 'none' })
      return false
    }
    // 最少
    if (type === 'sub') {
      App.WxService.showToast({ title: '不能再少了哦', icon: 'none' })
      return false
    }
  },
  // 获取商品详情
  getGoodsDetail() {
    const params = {
      id: this.data.id
      //   specialCode: this.data.scode,
    }
    this.setData({
      loading: true
    })
    // 商品详情接口
    ModelGoods.getGoodsDetail(params)
      .then(res => {
        //20190319 刘飞
        //商品详情接口整合普通，商城，秒杀三种商品
        //modelStatus == 1
        // 缩略图
        if (res.data.goodsDetail.showList.length > 0) {
          this.data.thumb = res.data.goodsDetail.showList[0].goodsImg
        } else {
          this.data.thumb = '%ASSETS_IMG%/c-face1@2x.png'
        }
        if (res.data.evaluate) {
          for (var i in res.data.evaluate) {
            if (res.data.evaluate[i].evaluateDes) {
              res.data.evaluate[i].evaluateDes = decodeUnicode(res.data.evaluate[i].evaluateDes)
            }
          }
        }
        //发货地判断
        if (res.data.cityName == '市辖区') {
          res.data.goodsDetail.addressName = res.data.provinceName
        } else {
          res.data.goodsDetail.addressName = res.data.cityName
        }
        // res.data.goodsDetail.endDate = res.data.endDate
        if (res.data.modelStatus != 3) {
          this.setData({
            evaluateNum: res.data.evaluateNum,
            evaluate: res.data.evaluate
          })
        }
        this.setData({
          goodsDetail: res.data.goodsDetail,
          goodsStatus: res.data.goodsStatus,
          modelStatus: res.data.modelStatus,
          showList: res.data.goodsDetail.showList,
          stock: res.data.goodsDetail.availableStock,
          thumb: `${this.data.thumb}?imageMogr2/thumbnail/120x120`,
          shareImg: `${this.data.thumb}?imageMogr2/thumbnail/500x500`,
          loading: false,
          seckill: false,
          hotGoods: res.data.goodsList
        })
        //判断是不是秒杀商品
        if (res.data.modelStatus == 3) {
          let seckillDate = this.data.seckillDate
          this.data.seckill = true
          if (res.data.specialStatus == 1) {
            this.data.seckillNow = true
            this.data.secKillTomorrow = false
            seckillDate = res.data.endDate
          } else if (res.data.specialStatus == 2) {
            this.data.seckillNow = false
            this.data.secKillTomorrow = true
            seckillDate = res.data.startDate
          }
          this.setData({
            seckill: this.data.seckill,
            seckillNow: this.data.seckillNow,
            secKillTomorrow: this.data.secKillTomorrow,
            specialStatus: res.data.specialStatus,
            seckillDate: seckillDate,
            specialCode: res.data.specialCode,
            quicklyStatus: res.data.quicklyStatus,
            seckillId: res.data.seckillId,
            seckillGoodsId: res.data.seckillGoodsId,
            specialInfo: res.data.specialInfo,
            hotGoods: res.data.goodsList
          })
        }
        // 如果是活动商品--专场
        if (this.data.modelStatus == 2) {
          this.setData({
            specialId: res.data.specialId,
            specialCode: res.data.specialCode,
            startDate: res.data.startDate,
            endDate: res.data.endDate,
            specialNotice: res.data.specialNotice,
            hotGoods: res.data.goodsList
          })
          this.goodsDetailCountdown(this.data.endDate)
          // 畅销商品
          // this.getHotGoods()
        }
        // 统计数据
        this.setGio()
        wx.stopPullDownRefresh()
      })
      .catch(err => {
        if (err.status == 400068 || err.status == 400106) {
          // 活动下架，获取推荐专场列表
          // this.getRecommend()
          this.setData({
            saleOff: true,
            loading: false
          })
        }
      })
  },
  // 推荐专场小轮播
  getRecommend() {
    const self = this
    const params = {}
    ModelHome.getBannerList(params)
      .then(res => {
        self.setData({
          saleOff: true,
          minBanner: res.data.minBannerList // 小轮播
        })
      })
      .catch(err => {})
  },
  // 获取畅销商品
  getHotGoods() {
    const self = this
    const params = {
      goodsId: this.data.id,
      specialCode: this.data.specialCode
    }
    ModelGoods.getHotGoods(params)
      .then(res => {
        self.setData({
          hotGoods: res.data.goodsList // 热门
        })
      })
      .catch(err => {})
  },

  // 获取商品尺码
  getGoodSpec() {
    // 商品尺码接口
    ModelGoods.getGoodSpec({
      goodsId: this.data.id
    }).then(res => {
      this.setData({
        specList: res.data.specNameList,
        skuVisible: true
      })
    })
  },
  // 下单
  showSku() {
    if (this.data.goodsDetail.availableStock == 0) {
      App.WxService.showToast({ title: '商品暂无库存', icon: 'none' })
      return
    } else {
      // 点击下单按钮请求尺码
      this.getGoodSpec()
    }
  },

  //倒计时
  goodsDetailCountdown(time) {
    const self = this
    new $CountDown({
      date: time,
      render(date) {
        const days = this.leadingZeros(date.days, 1)
        const hours = this.leadingZeros(date.hours, 2)
        const min = this.leadingZeros(date.min, 2)
        const sec = this.leadingZeros(date.sec, 2)
        self.setData({
          days: days,
          hours: hours,
          min: min,
          sec: sec
        })
      }
    })
  },
  // 关闭下单
  closeSku() {
    this.setData({
      skuVisible: false
    })
  },
  // 选择尺码
  chooseSpec(options) {
    var index = parseInt(options.currentTarget.dataset.index)
    let stock = this.data.specList[index].availableStock
    // 重新设置
    this.setData({
      goodsNum: 1
    })
    //设置当前样式
    this.setData({
      activeIndex: index,
      stock: stock
    })
  },
  //
  onChange(e) {
    //数量判断
    if (e.detail.value >= this.data.stock) {
      e.detail.value = this.data.stock
    }
    if (e.detail.value < 0) {
      e.detail.value = 1
    }
    // 设置金额
    this.setData({
      goodsNum: e.detail.value
    })
  },
  // 添加购物车
  doAddCart() {
    if (this.data.activeIndex == null) {
      App.WxService.showToast({ title: '请选择尺码', icon: 'none' })
      return
    }
    const index = this.data.activeIndex
    // 添加购物车接口
    ModelGoods.addShopCart({
      specialId: this.data.specialId,
      warehouseId: this.data.specList[index].warehouseId,
      stockId: this.data.specList[index].id,
      cartNum: this.data.goodsNum,
      status: this.data.cartStatus,
      remark: ''
    }).then(res => {
      this.setData({
        skuVisible: false
      })
      App.WxService.showToast({
        title: res.info,
        duration: 1000
      })
      setTimeout(() => {
        this.selectCartNumber()
      }, 1000)
    })
  },

  // 立即购买
  doBuyNow() {
    if (this.data.activeIndex == null) {
      App.WxService.showToast({ title: '请选择尺码', icon: 'none' })
      return
    }
    const index = this.data.activeIndex
    // 立即购买接口
    const params = {
      specialId: this.data.specialId,
      warehouseId: this.data.specList[index].warehouseId,
      stockId: this.data.specList[index].id,
      cartNum: this.data.goodsNum,
      status: this.data.cartStatus
    }
    ModelGoods.buyNow(params).then(res => {
      App.WxService.navigateTo(`/packCart/pages/payOrder/index?ids=${res.data.cartId}`)
    })
  },
  goShopcart() {
    App.WxService.navigateTo(`/packCart/pages/shopCar/index?from=goods`)
  },

  //查看发现列表
  discover: function() {
    const specialId = this.data.specialId
    wx.navigateTo({
      url: `/pages/home/discover/index?specialId=${specialId}`
    })
  },
  //缩略图
  preview: function(e) {
    const url = e.currentTarget.dataset.url
    const urls = e.currentTarget.dataset.urls
    const urlArr = []
    for (var i = 0; i < urls.length; i++) {
      urlArr.push(urls[i].imgUrl)
    }
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: urlArr // 需要预览的图片http链接列表
    })
  },
  shareGoods() {
    // 分享商品
    const shareInfo = this.data.goodsDetail
    const ucode = App.globalData.userInfo.userCode
    this.setData({
      showShare: true,
      showType: 'goods',
      shareData: {
        shareTitle: shareInfo.goodsName,
        id: shareInfo.id,
        specialCode: this.data.scode,
        goodsImg: this.data.shareImg,
        goodsName: shareInfo.goodsName,
        goodsMoney: shareInfo.goodsMoney,
        goodsPrice: shareInfo.goodsPrice,
        discount: shareInfo.discount,
        startDate: this.data.startDate,
        endDate: this.data.endDate,
        // sharePath: `/pages/goodsDetail/index?id=${this.data.id}&scode=${this.data.scode}&bossid=${ucode}`,
        sharePath: `/pages/goodsDetail/index?id=${this.data.id}&bossid=${ucode}`,
        shareImg: this.data.shareImg,
        showTime: shareInfo.showTime, // 几点场次
        modelStatus: this.data.modelStatus, // 商品类型
        specialStatus: this.data.specialStatus //1. 快抢中 2. 快抢预告
      }
    })
  },

  //获取购物车商品数量
  selectCartNumber() {
    const self = this
    const params = {}
    ModelApp.selectCartNumber(params)
      .then(res => {
        self.setData({
          shopCartNum: res.data.number.liteCart
        })
      })
      .catch()
  },
  //快抢提醒
  remind: function() {
    const that = this
    let quicklyStatus = that.data.quicklyStatus
    if (quicklyStatus == 1) {
      wx.showToast({
        title: '已设置开抢提醒',
        icon: 'success',
        duration: 2000
      })
      return
    } else {
      const params = {
        seckillId: that.data.seckillId,
        seckillGoodsId: that.data.seckillGoodsId
      }

      ModelSeckill.makeSeckillGoods(params)
        .then(res => {
          quicklyStatus = 1
          that.setData({
            quicklyStatus: quicklyStatus
          })
          wx.showToast({
            title: '提醒已设置，将在开抢前十分钟提醒你',
            duration: 1000,
            icon: 'none',
            success: function() {}
          })
        })
        .catch()
    }
  },
  onShareAppMessage: function(ops) {
    // button分享和右上角分享信息一样不用判断ops.from
    const that = this
    if (ops.from === 'button') {
      // 来自页面内转发按钮
      const shareInfo = ops.target.dataset.share
      console.log(shareInfo)
      that.path = shareInfo.sharePath
      that.title = shareInfo.shareTitle
      that.img = shareInfo.shareImg
    }
    return {
      title: that.title,
      path: that.path,
      imageUrl: that.img
    }
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    // 获取购物车数量
    this.selectCartNumber()
    // 获取商品详情
    this.getGoodsDetail()
  },

  // 获取滚动条当前位置
  // onPageScroll: function(e) {
  //   const self = this
  //   wx.getSystemInfo({
  //     success: function(res) {
  //       if (e.scrollTop > res.windowHeight) {
  //         self.setData({
  //           floorstatus: true
  //         })
  //       } else {
  //         self.setData({
  //           floorstatus: false
  //         })
  //       }
  //     }
  //   })
  // },
  onPageScroll: function(res) {
    // 获取 滚动高度
    let _this = this
    const wHight = App.globalData.mobile.windowHeight
    let scrollTop = res.scrollTop
    // 滚动大于屏幕高度
    if (scrollTop > wHight && !_this.data.floorstatus) {
      _this.setData({
        floorstatus: true
      })
    } else if (scrollTop < wHight && _this.data.floorstatus) {
      _this.setData({
        floorstatus: false
      })
    }
  },
  // 点击触发显示新手指导和新用户直接弹
  emitShowGuide() {
    this.setData({
      wiggle: false
    })
    if (this.data.userType == 1) {
      // this.setData({
      //   guideVisible: true
      // })
      this.shareGoods()
    } else {
      // 其他用户弹出详情分享
      this.shareGoods()
    }
  },
  // 停止分享icon晃动
  doStopWiggle() {
    this.setData({
      wiggle: true
    })
  },
  // 获取粉丝
  getFans() {
    //获取当前用户类型，佣金，粉丝，邀请人信息
    managerModel
      .getFansInfo()
      .then(res => {
        // 获取还有多少粉丝升级
        const guideInfo = res.data
        guideInfo.userImg = App.globalData.userInfo.userImg
        this.setData({
          userType: res.data.userType,
          guideInfo: guideInfo
        })
        // if (res.data.userType == 1) {
        //   // 普通用户分享
        //   if (App.globalData.levelFlag) {
        //     this.setData({
        //       showGuide:true
        //     })
        //     App.globalData.levelFlag = false
        //   }
        // }
      })
      .catch(err => {})
  },
  // 最后疯抢
  getBannerList() {
    const self = this
    const params = {}
    ModelHome.queryCrazy()
      .then(res => {
        self.setData({
          minBanner: res.data.classList // 小轮播
        })
      })
      .catch(err => {})
  },
  // 去搜索页品牌
  goSearchBrand(e) {
    const brandid = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/search/index?brand=${brandid}&type=click`
    })
  },

  //跳转关联专场
  tapToSpecial() {
    const specialCode = this.data.specialInfo.specialCode
    wx.navigateTo({
      url: `/pages/activity/index?scode=${specialCode}`
    })
  },
  //正品保障
  tapToQuality() {
    const bannerUrl = 'https://admin.top1buyer.com/wxview/quality'
    wx.navigateTo({
      url: `/pages/home/webview/index?bannerUrl=${bannerUrl}`
    })
  }
})
